const runtime = require("./runtime")
const { createExecutor } = require("./core/executor")
const { createScheduler } = require("./core/scheduler")


const ScriptEngine = function(properties) {
    Object.assign(this, properties || {}, {
        name: "脚本执行引擎",
        scheduler: undefined,
        executor: undefined,
        start: Date.now(),
    });
    this.initialize = function() {
        if (this.scheduler != undefined || this.executor != undefined) {
            toast("执行引擎已经初始化，请勿重复执行!")
            return false
        }
        //创建调度器
        this.scheduler = createScheduler()
        //创建执行器
        this.executor = createExecutor()
        //为调度器注册执行器,由调度器来提交和分发任务
        this.scheduler.registerExecutor(this.executor)
        //刷新配置
        this.refresh()
        return true
    },
    this.refresh = function() {
        //暂停执行器
        this.executor.pause()
        //刷新配置
        this.scheduler.refresh()
    },
    this.switch = function() {
        let result = this.executor.switch()
        console.info("执行引擎当前状态：" + (result ? "已启动" : "已暂停"))
        return result
    },
    this.release = function() {
        if (this.scheduler != undefined) {
            this.scheduler.release()
            this.scheduler = undefined
        }
        if (this.executor != undefined) {
            this.executor = undefined
        }
    },
    this.submit = function(task) {
        this.scheduler.submit(task)
    }
}

//全局唯一，脚本引擎对象
exports.engine = new ScriptEngine()